import datetime
from re import S
import db
import KBEDebug as log
import KBEngine


class LoginPlatform:
    def __init__(self, table_name):
        self.table_name = table_name
        self.tb = db.DBTable(table_name)
        # 平台类型
        self.tb.setFiled('platformId', db.UINT32())
        # 玩家数
        self.tb.setFiled('playerCount', db.UINT32())

    def createTable(self, success_callback):
        self.tb.exec(success_callback)


class ILoginPlatform:
    def __init__(self):
        self.tb_loginPlatform = LoginPlatform('lobby_login_platform')
        self.tb_create_count = 1
        self.tb_loginPlatform.createTable(self.createTableSuccess)

    def createTableSuccess(self):
        self.tb_create_count -= 1
        if self.tb_create_count <= 0:
            pass

    def updateOrCreateRecord(self, platform_id):
        def callback(record):
            if len(record) == 0:
                # 创建一条新记录
                info = {
                    'platformId': platform_id,
                    'playerCount': 1
                }
                self.tb_loginPlatform.tb.addLine(info)
                log.DEBUG_MSG(f'创建平台登录信息: {platform_id}')
            else:
                # 记录已存在，增加玩家数量
                sql = f'UPDATE lobby_login_platform SET playerCount = playerCount + 1 WHERE platformId = \"{platform_id}\"'
                log.DEBUG_MSG(f'更新平台登录记录: {platform_id}')
                KBEngine.executeRawDatabaseCommand(sql, None)
        
        self.tb_loginPlatform.tb.loadAll(f'platformId=\"{platform_id}\"', callback)
